package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;

/**
 *  HaiNanNewsAnalyse  海南在线新闻解析类
 *  xiaonie 2012-11-22
 */
public class HaiNanNewsAnalyse implements AnalyseNews{
	private final String[] regexs={ 
			"http://news.hainan.net/newshtml[0-9]{2}/.*/*[.]htm",
			"http://.*[.]hainan.net/.*/[0-9]{4}/[0-9]{2}/[0-9]{2}/[0-9]+[.]shtml"};

	
	public boolean isDetailPage(String url) {
		for (String regex : regexs) {
			if (url.matches(regex)) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String str_encode=urlMeta.getEncoding();
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		Document doc=Jsoup.parse(htmltxt);
		String title=null;
		String content=null;
		Long date=null;
		String dateStr=null;
		if (htmltxt != null && htmltxt != "") {
			news.setUrl(url);
			title=doc.select("div.subject").text();
			if(StringUtils.isBlank(title)){
				title=doc.select("div#box_content h1").text();
			}
			content=HtmlCleaner.getContentHtml(url,doc.select("div.content"));
			if(StringUtils.isBlank(content)){
				content=HtmlCleaner.getContentHtml(url,doc.select("div#box_content p"));
			}
			dateStr=doc.select("div.info,h2").text();
			date=DateUtils.matchDate(dateStr);
			/**
			 * 解析用于更新的地址
			 */
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(StringUtils.trimSpace(content));
			if(date==null){
				date=DateUtils.matchDate(url);
			}
			news.setDate(date);
			news.setClickNum(null);
			news.setType(1);
			
			String author=doc.select("div.info a").text();
			if(StringUtils.isBlank(author)){
				author=JSoupUtils.matchAuthor(doc, "来源：");
			}
			news.setAuthor(author);
		}
		return news;
	}

	public static void main(String[] args) {
		HaiNanNewsAnalyse a=new HaiNanNewsAnalyse();
		String url="http://finance.hainan.net/st/2014/05/12/1894554.shtml";
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(a.isDetailPage(url));
		NewsMeta parserHtml=a.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}
	
	public boolean isNeedUpdate(){
		return true;
	}
}
